package com.example.statistics.ui.purchase

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.PurchaseAgentBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.common.BaseLoadingListActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityForResult
import com.jhj.slimadapter.SlimAdapter
import com.jhj.slimadapter.holder.ViewInjector
import org.jetbrains.anko.backgroundDrawable
import org.jetbrains.anko.find
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textColor
import java.util.*

class PurchaseProductListActivity : BaseLoadingListActivity<PurchaseProductBean>() {


    private var agent: PurchaseAgentBean? = null
    val date = Date()

    override val title: String
        get() = agent?.agent ?: "采购"

    override val itemLayoutRes: Int
        get() = R.layout.list_item_purchase_product

    override val url: String
        get() = UrlConfig.PURCHASE_PRODUCT_LIST

    override val httpParams: MutableList<Pair<String, String>>
        get() {
            var agentId = ""
            if (agent != null && agent?.id != 0) {
                agentId = agent?.id.toString()
            }
            return mutableListOf("agentId" to agentId)
        }

    override val inputSearch: Boolean
        get() = true

    override val inputSearchFunc: (PurchaseProductBean, String) -> Boolean = { bean, str ->
        (bean.factoryNo + bean.productName).contains(str) || bean.containerNo.contains(str) || bean.contractNo.contains(
            str
        )
    }


    override fun initialize() {
        super.initialize()
        agent = intent.getSerializableExtra(Constants.DATA) as PurchaseAgentBean?
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        topBarRightImage {
            singleDialog("期货", "现货") {
                activityForResult<PurchaseProductEditActivity>(
                    Constants.ACTION to it,
                    Constants.PARENT_ID to agent?.id,
                    "rate" to agent?.advanceInterestRate
                ) {
                    refresh()
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        refresh()
    }

    override fun itemViewConvert(adapter: SlimAdapter, injector: ViewInjector, bean: PurchaseProductBean, position: Int) {

        val status: String
        val statusColorRes: Int
        val portInfo = bean.shippingInfo
        val salesNumber = bean.purchaseSalesList?.sumEx { it.salesNumber }?.toInt()
        val arrivalDate = portInfo?.arrivalDate.goTimeFormat()
        val warehousingDate = portInfo?.warehousingDate.goTimeFormat()
        val deliveryDate = portInfo?.deliveryDate.goTimeFormat()
        val isSettlement = bean.billTotalAmount in (bean.settlementTotalAmount - 2..bean.settlementTotalAmount + 2)


        //状态和颜色
        if (!bean.purchaseSalesList.isNullOrEmpty()) { //出库，拆柜、整除
            status = "$deliveryDate | "
            statusColorRes = if (salesNumber == bean.productNumber) R.color.red else R.color.dark_cyan
        } else if (!warehousingDate.isNullOrEmpty()) { //入库
            status = "$warehousingDate | "
            statusColorRes = R.color.blue
        } else if (!arrivalDate.isNullOrEmpty()) { //是否到港，
            status = "$arrivalDate | "
            statusColorRes = if (date.after(arrivalDate.parse())) R.color.orange else R.color.gray
        } else {
            status = "未装"
            statusColorRes = R.color.gray
        }
        if (!bean.purchaseSalesList.isNullOrEmpty() && bean.inventoryNumber == 0) {
            val salesTotalPrice = bean.purchaseSalesList?.sumEx { it.totalPrice }
            val profit = salesTotalPrice.subEx(bean.billTotalAmount)
            val number = if (bean.specification == "非定装")
                bean.productWeight
            else
                bean.productNumber

            val text = "成本:${bean.billTotalAmount.divEx(number)} " +
                    "| 售价:${salesTotalPrice.divEx(number)} " +
                    "| 盈亏:${profit} " +
                    "| 结清:${if (isSettlement) " 是" else "否"}"
            injector.visible(R.id.tv_text)
                .text(R.id.tv_text, text)
        } else {
            injector.gone(R.id.tv_text)
        }

        val index = if (agent?.id == 0) "${position + 1} | ${bean.agent}" else "${position + 1}"
        val number = if (bean.inventoryNumber == 0) bean.productNumber else bean.inventoryNumber
        injector.textColor(R.id.tv_title, getResColor(statusColorRes))
            .text(R.id.tv_title, bean.factoryNo + bean.productName)
            .text(R.id.tv_index, index)
            .text(R.id.tv_port_info, status + portInfo?.port.orEmpty() + portInfo?.coldStorage.orEmpty())
            .text(R.id.tv_container_no, "${bean.containerNo} | ${bean.contractNo}")
            .text(R.id.tv_number, "${number}件 | ${bean.priceUnit}${bean.productPrice}")
            //fileList
            .with<TextView>(R.id.tv_certificate) { textView ->
                if (!bean.fileList.isNullOrEmpty()) {
                    textView.visibility = View.VISIBLE
                    val isDeclaration = bean.fileList?.filter { it.name.contains("报关单") }?.size == 1
                    val isQuarantine = bean.fileList?.filter { it.name.contains("检疫") }?.size == 1
                    if (isDeclaration && isQuarantine) {
                        textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_purple)
                        textView.textColor = getResColor(R.color.purple)
                        textView.text = "双证"
                    } else if (isDeclaration) {
                        textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_cyan)
                        textView.textColor = getResColor(R.color.cyan)
                        textView.text = "报关单"
                    } else if (isQuarantine) {
                        textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_cyan)
                        textView.textColor = getResColor(R.color.cyan)
                        textView.text = "检疫"
                    } else {
                        textView.visibility = View.GONE
                    }
                } else {
                    textView.visibility = View.GONE
                }
            }
            .with { view ->
                //定金、尾款状态，1、预估，2预付，已付
                val deposit = view.find<TextView>(R.id.tv_deposit)
                val balance = view.find<TextView>(R.id.tv_balance)
                val clearance = view.find<TextView>(R.id.tv_clearance)

                //1、定金/尾款/出清没账单
                //2、定金/尾款/出清有付款日期没账单
                //3、定金/尾款/出清有付款账单
                //4、定金/尾款/出清已付
                var depositState = 0
                var balanceState = 0
                var clearanceState = 0
                bean.futuresFeeList?.forEach {
                    if (it.feeType.contains("定金") && it.rmb != 0.0) {
                        depositState = 3
                    } else if (it.feeType.contains("定金")) {
                        depositState = 2
                    } else if ((it.feeType.contains("尾款")) && it.rmb != 0.0) {
                        balanceState = 3
                    } else if ((it.feeType.contains("尾款"))) {
                        balanceState = 2
                    }
                }
                bean.settlementFeeList?.forEach {
                    if (it.type.contains("定金")) {
                        depositState = 4
                    } else if (it.type.contains("尾") || it.type.contains("清")) {
                        balanceState = 4
                    }
                    if (it.type.contains("清")) {
                        clearanceState = 4
                    }
                }

                settlementState(deposit, depositState)
                settlementState(balance, balanceState)
                settlementState(clearance, clearanceState)
            }
            .onActionLongClicked(
                "复制" to {
                    if (bean.futuresSpot == "现货") {
                        activityForResult<PurchaseSpotProductActivity>(
                            Constants.ACTION to Constants.ACTION_EDIT,
                            Constants.PURCHASE_PRODUCT_ID to bean.ID,
                            Constants.TITLE to bean.factoryNo + bean.productName
                        ) {

                        }
                    } else {
                        activityForResult<PurchaseFuturesProductActivity>(
                            Constants.ACTION to Constants.ACTION_EDIT,
                            Constants.PURCHASE_PRODUCT_ID to bean.ID,
                            Constants.TITLE to bean.factoryNo + bean.productName
                        ) {

                        }
                    }
                },
                "删除" to {
                    messageDialog(msg = "是否删除${bean.contractNo}?") { _, _ ->
                        httpGet<PurchaseProductBean>(
                            UrlConfig.PURCHASE_PRODUCT_DELETE,
                            config = {
                                listParams = listOf("id" to bean.ID)
                                isShowDialog = true
                            }) {
                            refresh()
                        }
                    }
                })
            .clicked {
                //查看
                if (bean.futuresSpot == "现货") {
                    startActivity<PurchaseSpotProductActivity>(
                        Constants.PURCHASE_PRODUCT_ID to bean.ID,
                        Constants.TITLE to bean.factoryNo + bean.productName
                    )
                } else {
                    startActivity<PurchaseFuturesProductActivity>(
                        Constants.PURCHASE_PRODUCT_ID to bean.ID,
                        Constants.TITLE to bean.factoryNo + bean.productName
                    )
                }
            }
    }


    private fun settlementState(textView: TextView, state: Int) {
        when (state) {
            4 -> {
                textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_purple)
                textView.textColor = getResColor(R.color.purple)
            }
            3 -> {
                textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_cyan)
                textView.textColor = getResColor(R.color.cyan)
            }
            2 -> {
                textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_cyan)
                textView.textColor = getResColor(R.color.gray)
            }
            else -> {
                textView.backgroundDrawable = getResDrawable(R.drawable.shape_frame_gray)
                textView.textColor = getResColor(R.color.gray)
            }
        }
    }
}